package com.oriole.admin.config.local;

import com.oriole.admin.config.TokenProvider;
import com.oriole.admin.utils.JacksonUtil;
import com.oriole.common.constant.Constants;
import com.oriole.common.constant.ResultModel;
import com.oriole.common.util.FastJsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author doublelife
 * Email: hautxxxyzjk@163.com
 * Date: 2019-03-28 21:31
 * Description:
 */
@Component
@ConditionalOnProperty(prefix = "oriole", name = "login-type", havingValue = "local")
public class OrioleJwtGenericFilterBean extends GenericFilterBean {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        String token = req.getHeader(Constants.HEADER_STRING);
        if (StringUtils.isNotBlank(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            String realToken = token.replace(Constants.TOKEN_PREFIX, "").replaceAll(" ", "");
            TokenProvider tokenProvider = new TokenProvider();
            if (tokenProvider.isExpired(realToken)) {
                response.setContentType(Constants.CONTENT_TYPE);
                PrintWriter writer = response.getWriter();
                writer.write(JacksonUtil.pojo2Json(new ResultModel<>(Constants.TOKEN_EXPIRED_CODE, Constants.TOKEN_EXPIRED_MSG)));
                writer.flush();
                writer.close();
                return;
            }
            Object principal = tokenProvider.getByTokenKey(realToken, Constants.JWT_PRINCIPAL);
            Object authoritiesStr = tokenProvider.getByTokenKey(realToken, Constants.JWT_AUTHORITIES);
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            if (authoritiesStr instanceof Collection) {
                authorities = FastJsonUtil.parseArray(FastJsonUtil.toJsonString(authoritiesStr), SimpleGrantedAuthority.class);
            }
            if (!ObjectUtils.isEmpty(principal)) {
                OrioleUsernamePasswordAuthenticationToken authenticationToken = new OrioleUsernamePasswordAuthenticationToken(principal, realToken, authorities);
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        filterChain.doFilter(request, response);
    }

}
